package com.xyz.messagehelper

import android.os.Message
import android.util.Log
import com.xyz.messagehelper.bean.ConstantValue
import com.xyz.messagehelper.bean.ConstantValue.SEND_MESSAGE
import com.xyz.messagehelper.bean.ConstantValue.SEND_MESSAGE_TASK_COMPLETE
import com.xyz.messagehelper.bean.ConstantValue.START_SEND_TASK_FAIL
import com.xyz.messagehelper.bean.MessageEvent
import com.xyz.messagehelper.utils.SharePreferenceUtils
import com.xyz.messagehelper.utils.Utils
import com.xyz.messagehelper.utils.Utils.getStringWithNumLength
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.FileOutputStream
import java.util.concurrent.atomic.AtomicBoolean

@Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class SendMessageRunnable : Runnable {

    //决定这个任务是否运行,或者结束当前的任务
    private val isRunning: AtomicBoolean = AtomicBoolean(true)

    private val lock = Object()

    //暂停当前的任务，或者唤醒当前的任务
    private val isPause: AtomicBoolean = AtomicBoolean(false)

    override fun run() {
        val path = SharePreferenceUtils.getString(Utils.context, "message_path", null)
        val messageRules = SharePreferenceUtils.getString(Utils.context, "message_rules", null)
        val timeInterval =
            SharePreferenceUtils.getString(Utils.context, "time_interval", "5").toInt()
        if (messageRules == null || path == null) {
            EventBus.getDefault().post(MessageEvent(START_SEND_TASK_FAIL))
        }

        val loggerFile =
            File(Utils.context.getExternalFilesDir("").path + File.separator + "taskLoggerFile.txt")
        if (!loggerFile.exists()) {
            loggerFile.createNewFile()
        }
        val outStream = FileOutputStream(loggerFile.absoluteFile)
        val timeStr = Utils.getTime() + "-" + Utils.getDate()
        outStream.write(timeStr.toByteArray())
        //开始运行以后，这里主要是字符串的替换
        val file = File(path)
        file.readLines().forEach {
            synchronized(lock) {
                if (isPause.get()) {
                    lock.wait()
                }
                if (!isRunning.get()) {
                    EventBus.getDefault().post(MessageEvent(SEND_MESSAGE_TASK_COMPLETE))
                    outStream.close()
                    return
                }
                val strArray = it.split(",")
                val length = strArray.size

                //第一行是手机联系人
                val phoneNumStr = strArray[0].trim()

                if (getStringWithNumLength(phoneNumStr) != 11) {
                    outStream.write("手机号错误:$phoneNumStr".toByteArray())
                    EventBus.getDefault().post(MessageEvent(ConstantValue.SENT_MESSAGE_FAIL))
                    outStream.close()
                    return
                }

                var messageContent: String = messageRules

                if (messageRules.contains("{date}")) {
                    messageContent = messageContent.replace("{date}", Utils.getDate())
                }

                if (messageRules.contains("{time}")) {
                    messageContent = messageContent.replace("{time}", Utils.getTime())
                }

                if (messageRules.contains("{var1}") && length >= 2) {
                    messageContent = messageContent.replace("{var1}", strArray[1])
                }

                if (messageRules.contains("{var2}") && length >= 3) {
                    messageContent = messageContent.replace("{var2}", strArray[2])
                }

                if (messageRules.contains("{var3}") && length >= 4) {
                    messageContent = messageContent.replace("{var3}", strArray[3])
                }

                outStream.write("发送手机号：${phoneNumStr}--发送短信内容：${messageContent}\n".toByteArray())
                Utils.sendMessage(Utils.context, phoneNumStr, messageContent)

                EventBus.getDefault().post(MessageEvent(SEND_MESSAGE, messageContent))

                Thread.sleep(timeInterval * 1000L)
            }
        }
        outStream.close()
        EventBus.getDefault().post(MessageEvent(SEND_MESSAGE_TASK_COMPLETE))
    }

    fun getIsRunning(): Boolean {
        return isRunning.get()
    }

    fun getIsPause(): Boolean {
        return isPause.get()
    }

    /**
     * 如果pause为true：阻塞当前的线程
     * 反之为false：释放当前锁
     */
    fun pauseTask(pause: Boolean): Boolean {
        if (!isRunning.get()) {
            //如果当前线程已经被销毁，则直接返回
            return false
        }
        if (pause) {
            //如果需要暂停当前的任务，
            if (isPause.get()) {
                //如果現在处于暂停的状态，return false
                return false
            } else {
                //如果现在没有处于暂停的状态，设置isPause变量为true，阻塞当前的线程
                isPause.set(true)
                return true
            }
        } else {
            //反之如果需要继续执行当前的任务，唤醒当前的线程，释放锁
            synchronized(lock) {
                lock.notify()
            }
            isPause.set(false)
            return true;
        }
    }

    fun destoryTask() {
        isRunning.set(false)
    }

    fun startTask() {
        isRunning.set(true)
    }


}